package com.cfm880.webview;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cfm880.webview.html.HtmlHttpImageGetter;
import com.cfm880.webview.html.MyTagHandler;


public class TextViewActivity extends AppCompatActivity implements View.OnClickListener{
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    private ScrollView mScrollView;
    private TextView tvHtml, tvTitle;
    private ImageView imUp, imCenter, imDown;
    ObjectAnimator longTimeAnimator, shortTimeAnimator;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view);
        init();
        DisplayMetrics metric = new DisplayMetrics();
        String html = Utils.getHtmlToString(this, R.raw.example);
        tvTitle.setText(Utils.getTitle(html));
        tvHtml.setText(Html.fromHtml(Utils.removeTitleTags(html),
                new HtmlHttpImageGetter(tvHtml),
                new MyTagHandler()));
    }




    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int height = tvHtml.getMeasuredHeight();
        mScrollView.setFocusable(false);
        imCenter.requestFocus();
        step = mScrollView.getBottom()/25 * 2;
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                longTimeAnimator = ObjectAnimator.ofFloat(tvHtml, "translationY", 0, 0-tvHtml.getMeasuredHeight() + mScrollView.getBottom()-3*step).setDuration(10000);

                longTimeAnimator.start();
                longTimeAnimator.setAutoCancel(true);
                longTimeAnimator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        imCenter.setImageResource(R.drawable.pause);
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        imCenter.setImageResource(R.drawable.play);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                        imCenter.setImageResource(R.drawable.play);

                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                        imCenter.setImageResource(R.drawable.pause);
                    }
                });
            }
        }, 3000);//3秒后执行Runnable中的run方法

    }





    private void init() {
        mContentView = findViewById(R.id.activity_text);
        tvHtml = (TextView) findViewById(R.id.html_text);
        mScrollView = (ScrollView) findViewById(R.id.web_container);
        mScrollView.requestDisallowInterceptTouchEvent(true);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        imUp = (ImageView) findViewById(R.id.im_up);
        imCenter = (ImageView) findViewById(R.id.im_center);
        imDown = (ImageView) findViewById(R.id.im_down);
        imCenter.requestFocus();

        imUp.setOnClickListener(this);
        imCenter.setOnClickListener(this);
        imDown.setOnClickListener(this);
        shortTimeAnimator = new ObjectAnimator();

    }

    int flag = 0;
    long time = 0;
    int step = 1000;
    int toPosition = 0;
    int tempPosition = 0;
    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.im_up:
                time = longTimeAnimator.getCurrentPlayTime();
                if (longTimeAnimator.isRunning()){
                    longTimeAnimator.cancel();
                }
                flag = 1;
                imCenter.setImageResource(R.drawable.play);
                toPosition = tempPosition + step;
                if (toPosition>0){
                    ObjectAnimator.ofFloat(tvHtml,"translationY", tempPosition, 0).setDuration(100).start();
                    Toast.makeText(getBaseContext(), "已到顶了",Toast.LENGTH_SHORT).show();
                    tempPosition = 0;
                } else {
                    ObjectAnimator.ofFloat(tvHtml,"translationY", tempPosition, toPosition).setDuration(100).start();
                    tempPosition = toPosition;
                }
                break;
            case R.id.im_center:
                if (flag == 0) {
                    flag = 1;
                    time = longTimeAnimator.getCurrentPlayTime();
                    System.out.println(longTimeAnimator);
                    longTimeAnimator.cancel();
                    imCenter.setImageResource(R.drawable.play);
                }else {
                    flag = 0;
                    longTimeAnimator.start();
                    longTimeAnimator.setCurrentPlayTime(time);
                    imCenter.setImageResource(R.drawable.pause);
                }
                break;
            case R.id.im_down:
                time = longTimeAnimator.getCurrentPlayTime();
                if (longTimeAnimator.isRunning()){
                    longTimeAnimator.cancel();
                }
                flag = 1;
                imCenter.setImageResource(R.drawable.play);
                toPosition = tempPosition - step;
                if (toPosition <= 0-tvHtml.getMeasuredHeight() + mScrollView.getBottom()-3*step){
                    ObjectAnimator.ofFloat(tvHtml, "translationY", tempPosition, 0-tvHtml.getMeasuredHeight() + mScrollView.getBottom()-3*step).setDuration(100);
                    tempPosition = 0-tvHtml.getMeasuredHeight()+ mScrollView.getBottom();
                    Toast.makeText(getBaseContext(), "已到底了",Toast.LENGTH_SHORT).show();
                }else {
                    ObjectAnimator.ofFloat(tvHtml,"translationY", tempPosition, toPosition).setDuration(100).start();
                    tempPosition = toPosition;
                }
                break;

        }

    }

    private void hide() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    //  按键处理
    int flagFullScreen=0;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_0){
            if (flagFullScreen == 0) {
                flagFullScreen = 1;
                delayedHide(UI_ANIMATION_DELAY);
            } else {
                flagFullScreen = 0;
                show();
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}
